package cn.iqianye.app.qmc

import android.content.DialogInterface
import android.os.Build
import android.os.Bundle
import android.os.StrictMode
import android.os.StrictMode.ThreadPolicy
import android.view.Menu
import android.view.MenuItem
import android.webkit.*
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import kotlinx.android.synthetic.main.activity_main.*
import java.net.URLEncoder


class MainActivity : AppCompatActivity() {
    private var cookie: String? = null
    private var webSettings: WebSettings? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        if (Build.VERSION.SDK_INT > 9) {
            val policy = ThreadPolicy.Builder().permitAll().build()
            StrictMode.setThreadPolicy(policy)
        }
        webSettings = webview.settings
        webview.addJavascriptInterface(this, "android") //添加js监听 这样html就能调用客户端

        webview.webChromeClient = WebChromeClient()
        val loginUrl = "https://xui.ptlogin2.qq.com/cgi-bin/xlogin?s_url=http%3A%2F%2Fy.qq.com"
        webview.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
                val cookieManager: CookieManager = CookieManager.getInstance()
                cookie = cookieManager.getCookie("https://y.qq.com")
                val result = NetUtils.post("id=0039MnYb0qxYhV", "https://qqmusic.api.zhenxin.xyz/song/url")
                val json: JSONObject = JSON.parseObject(result)
                val code = json.getIntValue("result")
                val data = json.getString("data")
                if (code == 100) {
                    val buttons: Map<String, DialogInterface.OnClickListener> = mapOf(
                        "确定" to DialogInterface.OnClickListener { _, _ ->
                            finish()
                        },
                        "播放" to DialogInterface.OnClickListener { _, _ ->
                            val mediaPlayer = ManagedMediaPlayer()
                            mediaPlayer.setDataSource(data)
                            mediaPlayer.isLooping = true
                            mediaPlayer.prepare()
                            mediaPlayer.start()
                        }
                    )
                    Utils.showMyDialog(
                        this@MainActivity,
                        "提示",
                        "无需设置Cookie\n已成功获取[周杰伦 - 晴天] 的链接\n$data",
                        buttons
                    )
                    return
                }
                if (url != loginUrl) {
                    webview.loadUrl(loginUrl)
                }
            }
        }

        // UA
        webSettings?.userAgentString = GlobalVal.ua

        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings?.javaScriptEnabled = true

        //缩放操作
        webSettings?.setSupportZoom(true) //支持缩放，默认为true。是下面那个的前提。

        webSettings?.builtInZoomControls = true //设置内置的缩放控件。若为false，则该WebView不可缩放

        webSettings?.displayZoomControls = false //隐藏原生的缩放控件

        // 5.1以上默认禁止了https和http混用，以下方式是开启
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings?.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }

        webview.loadUrl("about:blank")
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menu.add(1, 100, 0, "获取Cookie")
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        when (item.itemId) {
            100 -> {
                if (!cookie.isNullOrEmpty()) {
                    Utils.showMyDialog(this, "提示", "当前Cookie为:\n$cookie", mapOf(
                        "发送" to DialogInterface.OnClickListener { _, _ ->
                            val result: String? = NetUtils.post(
                                "data=${URLEncoder.encode(cookie, "UTF-8")}",
                                "https://qqmusic.api.zhenxin.xyz/user/setCookie"
                            )
                            result?.let { Utils.showMyDialog(this, "提示", it, mapOf("确定" to null)) }
                            webview.loadUrl("https://qqmusic.api.zhenxin.xyz/song/url?id=0039MnYb0qxYhV")
                        }
                    ))
                } else {
                    Utils.showMyDialog(this, "提示", "当前Cookie为空", mapOf("确定" to null))
                }
            }
        }
        return super.onOptionsItemSelected(item)
    }
}
